package array

//给定两个数组，编写一个函数来计算它们的交集

import (
	"fmt"
	"sort"
)

func Intersect(nums1 []int, nums2 []int) []int {

	// key指的是元素内容,value指的是元素个数
	hashTable1 := map[int]int{}
	hashTable2 := map[int]int{}

	for _, v := range nums1 {
		_, ok := hashTable1[v]
		fmt.Println(v, ok)
		if ok {
			hashTable1[v]++
		} else {
			hashTable1[v] = 1
		}
	}

	fmt.Println(hashTable1)

	for _, v := range nums2 {
		_, ok := hashTable2[v]
		if ok {
			hashTable2[v]++
		} else {
			hashTable2[v] = 1
		}
	}

	fmt.Println(hashTable2)

	res := []int{}

	for k1, v1 := range hashTable1 {
		if v2, ok := hashTable2[k1]; ok {
			var less int
			if v1 <= v2 {
				less = v1
			} else {
				less = v2
			}

			for i := 0; i < less; i++ {
				res = append(res, k1)
			}
		}
	}

	return res

}

func Intersect2(nums1 []int, nums2 []int) []int {
	sort.Ints(nums1)
	sort.Ints(nums2)

	len1, len2 := len(nums1), len(nums2)

	index1, index2 := 0, 0

	res := []int{}

	for index1 < len1 && index2 < len2 {
		if nums1[index1] < nums2[index2] {
			index1++
		} else if nums1[index1] > nums2[index2] {
			index2++
		} else {
			res = append(res, nums1[index1])
			index1++
			index2++
		}
	}

	return res
}
